{% extends "base.html" %}

{% block title %}近日均价 - 惠农平台{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-clock me-2"></i>农产品近日均价</h3>
            </div>
            <div class="card-body">
                <!-- 筛选条件 -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <label for="priceTypeSelect" class="form-label">产品类型</label>
                        <select class="form-select" id="priceTypeSelect">
                            <option value="蔬菜" selected>蔬菜</option>
                            <option value="水果">水果</option>
                            <option value="粮食">粮食</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="daysSelect" class="form-label">统计天数</label>
                        <select class="form-select" id="daysSelect">
                            <option value="7" selected>最近7天</option>
                            <option value="15">最近15天</option>
                            <option value="30">最近30天</option>
                            <option value="60">最近60天</option>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="button" class="btn btn-primary" id="refreshRecentPricesBtn">
                            <i class="fas fa-refresh me-1"></i>刷新数据
                        </button>
                    </div>
                </div>

                <!-- 图表容器 -->
                <div class="chart-container">
                    <div id="recentPricesChart" style="width: 100%; height: 350px;"></div>
                </div>

                <!-- 价格趋势卡片 -->
                <div class="row mt-4" id="priceCardsRow">
                    <!-- 卡片内容将由JS动态填充 -->
                </div>

                <!-- 详细数据表格 -->
                <div class="mt-4">
                    <h5><i class="fas fa-table me-2"></i>详细价格数据</h5>
                    <div class="table-responsive">
                        <table class="table table-striped" id="recentPricesTable">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>平均价格</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 表格内容将由JS动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 说明信息 -->
                <div class="mt-4">
                    <div class="alert alert-info">
                        <h5><i class="fas fa-info-circle me-2"></i>数据说明</h5>
                        <ul class="mb-0">
                            <li>本页面展示了选定农产品的近日价格变化趋势</li>
                            <li>可以选择不同的产品类型和统计时间范围</li>
                            <li>价格变化百分比显示相对于前一天的变化</li>
                            <li>详细数据表格提供了每日的具体价格信息</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function updateAllRecentPrices() {
    // 刷新图表和下方卡片、表格
    initRecentPricesChart();
}

// 初始化"近日均价"图表和下方数据
async function initRecentPricesChart() {
    const chartContainer = document.getElementById('recentPricesChart');
    const type = document.getElementById('priceTypeSelect')?.value || '水果';
    const days = document.getElementById('daysSelect')?.value || 7;

    // 显示加载动画
    chartContainer.innerHTML = '<div class="d-flex justify-content-center align-items-center" style="height: 100%;"><div class="spinner-border text-success" role="status"><span class="visually-hidden">加载中...</span></div></div>';

    try {
        const response = await fetch(`/api/recent_prices?type=${type}&days=${days}`);
        const res = await response.json();

        if (res.code === 200 && res.data && res.data.series.length > 0) {
            const traces = res.data.series.map(s => ({
                x: res.data.dates,
                y: s.data,
                mode: 'lines+markers',
                name: s.name
            }));
            
            const layout = {
                title: '近日均价走势图',
                xaxis: { title: '日期' },
                yaxis: { title: '平均价格 (元)' },
                margin: { l: 50, r: 50, b: 50, t: 50 },
                legend: { x: 0, y: 1.1, orientation: 'h' }
            };
            chartContainer.innerHTML = ""; // 先清空loading动画
            Plotly.newPlot(chartContainer, traces, layout, {responsive: true});

            // 动态填充卡片和表格
            updatePriceCardsAndTable(res.data.dates, res.data.series[0].data);
        } else {
            chartContainer.innerHTML = `<div class="alert alert-warning">${res.message || '没有足够的数据来生成图表。'}</div>`;
            updatePriceCardsAndTable([], []);
        }
    } catch (error) {
        console.error('加载近日均价图表失败:', error);
        chartContainer.innerHTML = '<div class="alert alert-danger">加载图表时发生网络错误。</div>';
        updatePriceCardsAndTable([], []);
    }
}

// 动态更新下方卡片和表格
function updatePriceCardsAndTable(dates, prices) {
    // 卡片
    const cardsRow = document.getElementById('priceCardsRow');
    if (!dates.length || !prices.length) {
        cardsRow.innerHTML = '<div class="col-12 text-center text-muted">暂无数据</div>';
        document.querySelector('#recentPricesTable tbody').innerHTML = '';
        return;
    }
    // 计算今日均价、昨日均价、本周均价、本月均价、波动
    const todayPrice = prices[prices.length - 1];
    const yesterdayPrice = prices.length > 1 ? prices[prices.length - 2] : todayPrice;
    const weekAvg = (prices.slice(-7).reduce((a, b) => a + b, 0) / Math.min(7, prices.length)).toFixed(2);
    const monthAvg = (prices.slice(-30).reduce((a, b) => a + b, 0) / Math.min(30, prices.length)).toFixed(2);
    const fluctuation = (Math.max(...prices) - Math.min(...prices)) / (Math.max(...prices) || 1) * 100;

    cardsRow.innerHTML = `
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">今日均价</h5>
                    <h3 class="text-primary">¥${todayPrice.toFixed(2)}</h3>
                    <p class="text-muted">较昨日 <span class="${todayPrice >= yesterdayPrice ? 'text-success' : 'text-warning'}">${((todayPrice - yesterdayPrice) / (yesterdayPrice || 1) * 100).toFixed(1)}%</span></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">本周均价</h5>
                    <h3 class="text-primary">¥${weekAvg}</h3>
                    <p class="text-muted">近7天</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">本月均价</h5>
                    <h3 class="text-primary">¥${monthAvg}</h3>
                    <p class="text-muted">近30天</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">价格波动</h5>
                    <h3 class="text-primary">±${fluctuation.toFixed(1)}%</h3>
                    <p class="text-muted">波动范围</p>
                </div>
            </div>
        </div>
    `;

    // 表格
    let tableHtml = '';
    for (let i = dates.length - 1; i >= 0; i--) {
        tableHtml += `<tr>
            <td>${dates[i]}</td>
            <td>¥${prices[i].toFixed(2)}</td>
        </tr>`;
    }
    document.querySelector('#recentPricesTable tbody').innerHTML = tableHtml;
}

document.addEventListener('DOMContentLoaded', function() {
    // 页面加载完成后立即初始化所有内容
    updateAllRecentPrices();

    // 监听下拉框变化，自动刷新图表和数据
    document.getElementById('priceTypeSelect').addEventListener('change', updateAllRecentPrices);
    document.getElementById('daysSelect').addEventListener('change', updateAllRecentPrices);

    // 监听刷新按钮
    document.getElementById('refreshRecentPricesBtn').addEventListener('click', updateAllRecentPrices);
});
</script>
{% endblock %} 